#include <iostream>
#include <mutex>
#include <thread>
#include <chrono>

using namespace std;
using namespace chrono;


std::mutex lock_;

/// @brief 通过 run的true or false来控制两个线程的运行，
/// 且这两个线程的运行不会阻塞主线程
bool run = false;

void thread01() {
    while (true)
    {
        if (run == false)
        {
            std::cout << "thread1 quit!\n";
            return;
        }
        {
            std::lock_guard<std::mutex> guard(lock_);
            std::cout << "Hello, Concurrent World 01 !\n";
        }
        
        this_thread::sleep_for(microseconds(300));
    }
    
}

void thread02() {
    while (true)
    {
        if (run == false)
        {
            std::cout << "thread2 quit!\n";
            return;
        }
        {
            std::lock_guard<std::mutex> guard(lock_);
            std::cout << "Hello, Concurrent World 02 !\n";
        }
        this_thread::sleep_for(microseconds(300));
    }
    
}

int main()
{
    run = true;

    std::thread t1(thread01);

    std::thread t2(thread02);

    int cnt = 0;
    while (cnt < 10)
    {
        {
            std::lock_guard<std::mutex> guard(lock_);
            std::cout << "the joinable of t1 is: " << t1.joinable() << std::endl;
            std::cout << "the joinable of t2 is: " << t2.joinable() << std::endl;
        }
        this_thread::sleep_for(microseconds(2000));
        //Sleep(2000);
        cnt++;
    }

    t1.detach();
    t2.detach();

    cnt = 0;
    while (cnt < 5)
    {
        {
            std::lock_guard<std::mutex> guard(lock_);
            std::cout << "the joinable of t1 is: " << t1.joinable() << std::endl;
            std::cout << "the joinable of t2 is: " << t2.joinable() << std::endl;
        }
        this_thread::sleep_for(microseconds(1000));
        //Sleep(1000);
        cnt++;
    }

    run = false;

    cnt = 0;
    while (cnt < 5)
    {
        {
            std::lock_guard<std::mutex> guard(lock_);
            std::cout << "the joinable of t1 is: " << t1.joinable() << std::endl;
            std::cout << "the joinable of t2 is: " << t2.joinable() << std::endl;
        }
        this_thread::sleep_for(microseconds(2000));
        //Sleep(1000);
        cnt++;
    }

    std::cout << "over!\n";
    return 0;
}
